import { createSlice } from '@reduxjs/toolkit'
import axios from "axios"

const foodsStores = createSlice({
    name: "foods",
    initialState: {
        foodsListArr:[],
        menuIndex:0,
        cartList: [],
    },
    reducers: {
       setFoodsList(state,action){
        state.foodsListArr = action.payload
       },
       setMenuIndex(state,auction){
        state.menuIndex = auction.payload
       },
       addCartList(state,auction){
        const res = state.cartList.find( item =>{
            item.count = 1
            return item.id === auction.payload.id
        })
        console.log(res)
        if( res ){
            console.log(state.cartList)
            res.count += 1
        } else {
            state.cartList.push(auction.payload)
        }
       }
    },
})

const { setFoodsList, setMenuIndex, addCartList } = foodsStores.actions
// 异步
const getFoodsList = () => {
    return async(dispatch) => {
       const res = await axios.get('http://localhost:3004/takeaway')
       dispatch(setFoodsList(res.data))
    }
}
export { getFoodsList, setMenuIndex, addCartList }

const reducer = foodsStores.reducer

export default reducer